import axios from 'axios';
import { message as antdMessage } from 'antd'
export const request = axios.create({
  // 超时
  timeout: 10000,
  timeoutErrorMessage: '链接超时...'
})


// 请求拦截器
request.interceptors.request.use((config) => {
  // 携带token
  const token = localStorage.getItem('token');
  if(token) {
    config.headers.token = token
  }

  return config
}, (error) => {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(response => {
  // 拦截 
  if(response) {
    const { code, message } = response.data;

    switch(code) {
      case 200:
        antdMessage.success(message);
        break;
      case 400:
        antdMessage.error(message)
        break;
    }
  }

  return response
}, error => {
  // 拦截 http 状态
  if(error) {
    if(error.response) {
      const { status } = error.response;
      switch(status) {
        case 404: 
          antdMessage.error('资源没找到！！！');
          break;
      }
     }
  }
  return Promise.reject(error)
})